package top.laoshuzi.server.camera.service.impl

import com.alibaba.fastjson.JSON
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import top.laoshuzi.server.camera.bean.dto.CameraTargetCmdDTO
import top.laoshuzi.server.camera.bean.dto.CameraTargetDTO
import top.laoshuzi.server.camera.config.CameraConstant
import top.laoshuzi.server.camera.mqtt.MqttTemplate
import top.laoshuzi.server.camera.service.CameraService
import top.laoshuzi.server.common.exception.BizException

@Service
class CameraServiceImpl : CameraService {


    @Autowired
    private lateinit var mqttTemplate: MqttTemplate

    override fun controlDirection(id: String, cameraTarget: CameraTargetDTO) {

        val angularRange = IntRange(0, 180)
        if (!angularRange.contains(cameraTarget.angular))
            throw BizException().apply { errorMessage = "角度范围越界" }

        val angularData = 500 + 2000 * cameraTarget.angular / 180

        val angularLowBit = angularData.and(0xff)
        val angularHightBit = angularData.shr(8).and(0xff)

        val cmd = CameraTargetCmdDTO().apply {
            serial_data = listOf(
                    0xff,
                    0x2,
                    cameraTarget.num,
                    angularLowBit,
                    angularHightBit
            )
        }
        mqttTemplate.sendToMqtt(CameraConstant.TOPIC_CAMERA_TARGET.replace("{id}", id), JSON.toJSONString(cmd))
    }

}